// function getCharCoordinates(element) {
//     const range = document.createRange();
//     const chars = [];
//     // 递归遍历所有文本节点
//     function traverse(node) {
//         if (node.nodeType === Node.TEXT_NODE) {
//             for (let i = 0; i < node.length; i++) {
//                 range.setStart(node, i);
//                 range.setEnd(node, i + 1);
//                 const rect = range.getBoundingClientRect();
//                 if (rect.width > 0 && rect.height > 0) { // 过滤不可见字符
//                     chars.push({
//                         char: node.data[i],
//                         x: rect.left + window.scrollX,
//                         y: rect.top + window.scrollY,
//                         width: rect.width,
//                         height: rect.height
//                     });
//                 }
//             }
//         } else {
//             node.childNodes.forEach(traverse);
//         }
//     }
//     traverse(element);
//     return chars;
// }

function getCharCoordinates(element) {
    const range = document.createRange();
    const chars = [];

    // 检查字素分割支持
    const supportsGrapheme = typeof Intl?.Segmenter === 'function';
    const segmenter = supportsGrapheme
        ? new Intl.Segmenter('en', { granularity: 'grapheme' })
        : null;

    function processTextNode(node) {
        // 检查节点或其父元素是否隐藏
        function isHidden(element) {
            if (!element) return false;
            const style = window.getComputedStyle(element);
            return style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0';
        }

        // 如果节点或其父节点隐藏，则直接返回
        if (isHidden(node.parentElement)) {
            console.log("hidden element, text:", node.data)
            return;
        }

        const text = node.data;
        if (supportsGrapheme) {
            const segments = [...segmenter.segment(text)];
            for (const { segment, index } of segments) {
                range.setStart(node, index);
                range.setEnd(node, index + segment.length);
                addCharRect(segment);
            }
        } else {
            // 降级：处理代理对
            let i = 0;
            while (i < text.length) {
                const char = text[i];
                const charLength = isHighSurrogate(char) ? 2 : 1;
                range.setStart(node, i);
                range.setEnd(node, i + charLength);
                addCharRect(text.substring(i, i + charLength));
                i += charLength;
            }
        }
    }

    function isHighSurrogate(char) {
        const code = char.charCodeAt(0);
        return code >= 0xD800 && code <= 0xDBFF;
    }

    function addCharRect(char) {
        const rect = range.getBoundingClientRect();
        if (rect.width === 0 && rect.height === 0) return;

        // 处理祖先滚动偏移
        const { x: absX, y: absY } = getAbsoluteOffset(rect);
        chars.push({ char, x: absX, y: absY, width: rect.width, height: rect.height });
    }

    function getAbsoluteOffset(rect) {
        let x = rect.left, y = rect.top;
        let current = range.commonAncestorContainer;
        while (current && current !== document) {
            if (current.scrollLeft !== undefined) {
                x -= current.scrollLeft;
                y -= current.scrollTop;
            }
            current = current.parentNode || current.host;
        }
        return { x: x + window.scrollX, y: y + window.scrollY };
    }

    function traverse(node) {
        if (node.nodeType === Node.TEXT_NODE) {
            processTextNode(node);
        } else if (node.nodeType === Node.ELEMENT_NODE) {
            // 进入Shadow DOM
            if (node.shadowRoot) traverse(node.shadowRoot);
            node.childNodes.forEach(traverse);
        }
    }

    traverse(element);
    return chars;
}


chrome.runtime.onMessage.addListener(msg => {
    if (msg.action === 'annotateScreenshot') {
        const chars = getCharCoordinates(document.body);
        console.log("chars", chars);
        if ('paintWorklet' in CSS) {
            console.log("found");
            // 将坐标数据作为 CSS 变量传递
            // document.body.style.setProperty('--char-coords', JSON.stringify(chars));
            console.log("chars json", JSON.stringify(chars));
            // console.log(document.body.width, document.body.height);
            captureScreen(chars);
        } else {
            console.log("not found");
        }
    } else if (msg.action === 'getIt') {
        getIt();
    } else if (msg.action === "getTextPositions") {
        // 获取视口宽度（包括滚动条）
        let viewportWidth = window.innerWidth;
        // 获取视口高度（包括滚动条）
        let viewportHeight = window.innerHeight;
        console.log(viewportWidth, viewportHeight);
        const chars = getCharCoordinates(document.body);
        console.log("chars", chars);
        viewportWidth = window.innerWidth;
        // 获取视口高度（包括滚动条）
        viewportHeight = window.innerHeight;
        console.log(viewportWidth, viewportHeight);
        const dataStr = JSON.stringify(chars, null, 2);
        const dataUri = `data:application/json;charset=utf-8,${encodeURIComponent(dataStr)}`;

        const exportFileDefaultName = `text-positions-${new Date().toISOString().slice(0, 10)}.json`;

        const linkElement = document.createElement('a');
        linkElement.setAttribute('href', dataUri);
        linkElement.setAttribute('download', exportFileDefaultName);
        linkElement.click();
    } else {
    }
});



async function captureScreen(charPositions) {
    console.log("captureScreen start");
    const element = document.body;
    const canvas = await html2canvas(element, {
        scale: window.devicePixelRatio,
        width: element.offsetWidth,   // 元素逻辑宽度
        height: element.offsetHeight, // 元素逻辑高度
    });
    console.log(canvas)
    const styleString = canvas.style;
    console.log(canvas.style.width, canvas.style.height, canvas.style)
    // 2. 构建样式对象
    const styleObject = canvas.style;
    // 提取数值
    const widthNum = parseFloat(styleObject.width); // 1467
    const heightNum = parseFloat(styleObject.height); // 1313
    // const widthNum = canvas.width; // 1467
    // const heightNum = canvas.height; // 1313
    console.log(widthNum, heightNum);

    // const scaleX = widthNum / canvas.width;  // 水平缩放比例
    // const scaleY = heightNum / canvas.height; // 垂直缩放比例
    // const scale = Math.min(scaleX, scaleY); // 取最小值确保等比例缩放

    const finalCanvas = document.createElement('canvas');
    finalCanvas.width = widthNum;
    finalCanvas.height = heightNum;
    const finalCtx = finalCanvas.getContext('2d');
    // finalCtx.drawImage(canvas, 0, 0);

    // // 计算缩放后的实际宽高（保持比例）
    // const scaledWidth = canvas.width * scale;
    // const scaledHeight = canvas.height * scale;

    // // 居中绘制（可选）
    // const offsetX = (widthNum - scaledWidth) / 2;
    // const offsetY = (heightNum - scaledHeight) / 2;

    // console.log(scaledWidth, scaledHeight, offsetX, offsetY);

    finalCtx.drawImage(
        canvas,
        0, 0, canvas.width, canvas.height, // 源图像区域
        0, 0, widthNum, heightNum    // 目标区域（缩放后）
    );

    // 3. 创建标注层Canvas
    const annotationCanvas = document.createElement('canvas');
    annotationCanvas.width = widthNum;
    annotationCanvas.height = heightNum;
    const ctx = annotationCanvas.getContext('2d');

    // 4. 绘制彩色矩形框
    const colors = ['rgba(255,0,0,0.3)', 'rgba(0,255,0,0.3)', 'rgba(0,0,255,0.3)'];
    charPositions.forEach((pos, index) => {
        if (pos.width != 0) {
            ctx.fillStyle = colors[index % colors.length];
            ctx.fillRect(
                pos.x,
                pos.y,
                pos.width,
                pos.height
            );
        }
    });

    finalCtx.drawImage(
        annotationCanvas,
        0, 0, annotationCanvas.width, annotationCanvas.height, // 源图像区域
        0, 0, widthNum, heightNum    // 目标区域（缩放后）
    );

    // 6. 触发下载
    const link = document.createElement('a');
    link.download = `annotated-screenshot-${Date.now()}.png`;
    link.href = finalCanvas.toDataURL('image/png');
    link.click();
}

